import customizedError from "./Error/customizedError.js";
import * as customizedErrorCode from "./Error/customizedErrorCode.js";
import { WAIT_SEC } from "./config.js";

export const AJAX = async function (url, data = null) {
  const data_ = data;
  const option = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data_),
  };
  try {
    const request = data_ !== null ? fetch(url, option) : fetch(url);
    const response = await Promise.race([request, timeOut(WAIT_SEC)]);
    if (!response.ok) throw customizedError(customizedErrorCode.IS_5XX_ERROR);
    const responseData = await response.json();
    return responseData;
  } catch (error) {
    if (!(error instanceof customizedError)) {
      throw new customizedError(customizedErrorCode.CONNECTION_FAIL);
    }
    console.log(error);

    throw error;
  }
};

const timeOut = function (WAIT_SEC) {
  return new Promise(function (_, reject) {
    setTimeout(() => {
      throw new customizedError(customizedErrorCode.NETWORK_SLOW);
    }, WAIT_SEC * 1000);
  });
};
